<template>
	<view class="container">
		<view class="top">
			<navigator url="/pages/index/index" open-type="switchTab">
				<image class="back" src="/static/images/白色左箭头.png" mode=""></image>
			</navigator>
			<view class="title">应急救援</view>
		</view>
		<!-- 地图 -->
		<view class="map-card">
			<map @markertap="handleMarkerTap" :latitude="latitude" :longitude="longitude" :markers="markers">
			</map>
		</view>

		<!-- 导航菜单 -->
		<view>
			<uni-card>
				<view class="uni-common-mt">
					<uni-segmented-control :current="current" :values="items" :style-type="styleType"
						:active-color="activeColor" @clickItem="onClickItem" />
				</view>
				<view class="content">
					<view v-if="current === 0" class="cur1">
						<uni-forms ref="Form" :modelValue="FormData">
							<uni-forms-item label="位置">
								<uni-easyinput v-model="FormData.rescuePosition" placeholder="请输入地址" />
							</uni-forms-item>
							<uni-forms-item label="求助人">
								<uni-easyinput v-model="name" placeholder="请输入求助人姓名" />
							</uni-forms-item>
							<uni-forms-item label="手机号">
								<uni-easyinput v-model="phone" placeholder="请输入联系方式" />
							</uni-forms-item>
							<uni-forms-item label="车牌号">
								<uni-data-select v-model="FormData.carId" :localdata="carList" placeholder="请选择车牌号" />
							</uni-forms-item>
						</uni-forms>
					</view>

					<view v-if="current === 1" class="cur1">
						<uni-forms ref="Form" :modelValue="FormData">
							<uni-forms-item label="位置">
								<uni-easyinput v-model="FormData.rescuePosition" placeholder="请输入地址" />
							</uni-forms-item>
							<uni-forms-item label="求助人">
								<uni-easyinput v-model="name" placeholder="请输入求助人姓名" />
							</uni-forms-item>
							<uni-forms-item label="手机号">
								<uni-easyinput v-model="phone" placeholder="请输入联系方式" />
							</uni-forms-item>
							<uni-forms-item label="车牌号">
								<uni-data-select v-model="FormData.carId" :localdata="carList" placeholder="请选择车牌号" />
							</uni-forms-item>
						</uni-forms>

					</view>

					<view v-if="current === 2" class="cur1">
						<uni-forms ref="Form" :modelValue="FormData">
							<uni-forms-item label="起点">
								<uni-easyinput v-model="FormData.rescuePosition" placeholder="请输入地址" />
							</uni-forms-item>
							<uni-forms-item label="终点">
								<uni-easyinput v-model="FormData.endPosition" placeholder="请输入地址" />
							</uni-forms-item>
							<uni-forms-item label="求助人">
								<uni-easyinput v-model="name" placeholder="请输入求助人姓名" />
							</uni-forms-item>
							<uni-forms-item label="手机号">
								<uni-easyinput v-model="phone" placeholder="请输入联系方式" />
							</uni-forms-item>
							<uni-forms-item label="车牌号">
								<uni-data-select v-model="FormData.carId" :localdata="carList" placeholder="请选择车牌号" />
							</uni-forms-item>
						</uni-forms>
					</view>
					<view class="btn">
						<u-button type="primary" shape="circle" color="#ff6128" icon="phone" text="呼叫救援"
							@click="rescue"></u-button>
						<view class="record" @click="toRescueRecord">救援记录>></view>
					</view>
				</view>
			</uni-card>
		</view>

		<!-- 评分区域 -->
		<view class="rate-area" v-if="showRate">
			<text class="rate-title">请对本次呼救体验评分：</text>
			<u-rate class="ratee" v-model="rating" :count="5" size="36" active-color="#ff6128" />
			<u-button type="primary" shape="circle" text="提交评分" class="submit-rate-btn" @click="submitRating" />
		</view>


		<view>
			<uni-card title="警务救助">
				<u-grid :border="false">
					<u-grid-item v-for="(item,index) in baseList" :key="index" @click="call(index)">
						<image :src="item.imgSrc" :style="{ width: '40rpx', height: '40rpx', marginTop: '20rpx' }">
						</image>
						<text class="grid-text">{{item.title}}</text>
					</u-grid-item>
				</u-grid>
				<u-toast ref="uToast" />
			</uni-card>
		</view>
	</view>
</template>

<script>
	import request from '../../../uitls/request';
	export default {
		data() {
			return {
				showRate: false,
				rating: 0,
				markers: [],
				baseList: [{
						imgSrc: '/static/images/jiaotong.png',
						title: '交通事故',
						phone: '110'
					},
					{
						imgSrc: '/static/images/huojing.png',
						title: '火警',
						phone: '119'
					},
					{
						imgSrc: '/static/images/jijiubao.png',
						title: '急救中心',
						phone: '120'
					},
					{
						imgSrc: '/static/images/jc.png',
						title: '公安报警',
						phone: '110'
					}
				],
				FormData: {
					rescuePosition: '',
					endPosition: '',
					userId: '',
					carId: '',
					rescueTime: '',
					rescueTypeId: ''
				},
				queryCar: {
					uid: ''
				},
				items: ['搭电', '换胎', '拖车'],
				current: 0,
				activeColor: '#007aff',
				styleType: 'text',
				latitude: '',
				longitude: '',
				phone: '',
				name: '',
				userId: '',
				carList: [],
				rescueId: '',
				statusInterval: null
			}
		},
		methods: {
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			call(index) {
				const phoneNumber = this.baseList[index].phone;
				uni.showModal({
					content: `是否拨打${phoneNumber}?`,
					success: (res) => {
						if (res.confirm) {

						}
					}
				});
			},
			getLocation() {
				uni.getLocation({
					success: (res) => {
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.markers = [{
							id: 999,
							latitude: res.latitude,
							longitude: res.longitude,
							iconPath: '/static/mplocation.png',
							height: 30,
							width: 30,
							callout: {
								content: '您的位置',
								// #ifndef H5
								color: '#e93d0d',
								fontSize: 15,
								// #endif
								display: 'ALWAYS',
								borderRadius: 20
							},

						}]
					}
				})
			},
			choseLocation() {
				const that = this;
				uni.chooseLocation({
					latitude: '',
					longitude: '',
					success(res) {
						that.FormData.rescuePosition = res.name
						that.latitude = res.latitude
						that.longitude = res.longitude
					}
				})
			},
			// 腾讯地图逆地理编码
			getAddressFromCoords(lng, lat) {
				request({
					url: 'mp/rescue/map/resolve?lat=34.827164&lng=113.552986',
					method: 'GET',
					success(res) {
						console.log(res)
						const addr = res.data.result.address
						this.FormData.rescuePosition = addr;
					}
				});
			},
			getCarList() {
				const that = this;
				request({
					url: '/bigbase/carInfo/list',
					data: this.queryCar,
					method: 'GET',
					success(res) {
						that.carList = res.data.rows.map(car => ({
							value: car.id,
							text: car.carNum
						}));
					}
				})
			},
			getNowTime() {
				const date = new Date();

				const Y = date.getFullYear();
				const M = this.padZero(date.getMonth() + 1);
				const D = this.padZero(date.getDate());
				const h = this.padZero(date.getHours());
				const m = this.padZero(date.getMinutes());
				const s = this.padZero(date.getSeconds());

				return `${Y}-${M}-${D} ${h}:${m}:${s}`;
			},
			padZero(n) {
				return n < 10 ? '0' + n : n;
			},
			rescue() {
				this.FormData.userId = this.userId;
				this.FormData.rescueTypeId = this.current + 1;
				this.FormData.rescueTime = this.getNowTime();

				request({
					url: '/mp/rescue/add',
					method: 'POST',
					data: this.FormData,
					success: (res) => {
						this.rescueId = res.data.data;

						// 发通知
						request({
							url: '/notice/notice/rescueMessage',
							method: 'POST',
							data: {
								uid: this.userId,
								title: '救援任务',
								content: '该用户急需' + this.items[this.current],
								hid: String(this.rescueId)
							},
							success: () => {
								uni.showLoading({
									title: '正在呼叫救援，请耐心等待',
									mask: true
								});
								
								this.statusInterval = setInterval(() => {
									this.checkRescueStatus1();
								}, 5000);

								// 70秒后检查救援状态
								setTimeout(() => {
									this.checkRescueStatus();
								}, 70000);
							}
						});
					}
				});
			},
			toRescueRecord() {
				uni.navigateTo({
					url: '/pages/zwj/jiuyuanjilu/jiuyuanjilu'
				})
			},
			checkRescueStatus() {
				request({
					url: `/mp/rescue/` + this.rescueId,
					method: 'GET',
					success: (res) => {
						uni.hideLoading();
						const rescueData = res.data.data;

						if (!rescueData.merchantId) {
							uni.showModal({
								title: '无人接单',
								content: '当前暂无商家接单，您可以稍后重新发起救援。',
								showCancel: false
							});
							request({
								url: '/mp/rescue/' + this.rescueId,
								method: 'DELETE'
							})
						} else {
							uni.showModal({
								title: '救援已响应',
								content: '商家正在赶来，请不要离开当前位置。',
								showCancel: false,
								success: () => {
									this.showRate = true;
								}
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '状态检查失败',
							icon: 'none'
						});
					}
				});
			},
			checkRescueStatus1() {
				request({
					url: `/mp/rescue/` + this.rescueId,
					method: 'GET',
					success: (res) => {
						const rescueData = res.data.data;
						if (rescueData.merchantId) {
							clearInterval(this.statusInterval);
							uni.hideLoading();
							uni.showModal({
								title: '救援已响应',
								content: '商家正在赶来，请不要离开当前位置。',
								showCancel: false,
								success: () => {
									this.showRate = true;
								}
							});
						} 
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '状态检查失败',
							icon: 'none'
						});
					}
				});
			},
			submitRating() {
				if (this.rating === 0) {
					uni.showToast({
						title: '请先选择评分',
						icon: 'none'
					});
					return;
				}

				request({
					url: '/mp/rescue',
					method: 'PUT',
					data: {
						id: this.rescueId,
						score: this.rating
					},
					success: () => {
						uni.showToast({
							title: '感谢您的反馈！',
							icon: 'success'
						});
						this.showRate = false;
					}
				});
			}

		},
		onLoad() {
			// #ifndef H5
			this.choseLocation();
			// #endif 
			// #ifdef H5
			this.getLocation();
			// #endif
			const userInfo = uni.getStorageSync('userInfo');
			this.phone = userInfo.phone
			this.name = userInfo.userName
			this.userId = userInfo.id
			this.queryCar.uid = this.userId
			this.getCarList()
		}
	}
</script>

<style scoped>
	.container {
		/* #ifdef MP-WEIXIN */
		padding-top: 60rpx;
		/* #endif */
		background: linear-gradient(180deg, #FF9800, #F44336);
		background-size: 100% 40%;
		background-repeat: no-repeat;
		min-height: 100vh;
		padding-bottom: 30rpx;
	}

	/* 背景图片 */
	.top {
		width: 100%;
		margin-bottom: 50rpx;
	}

	.top .back {
		position: absolute;
		margin-left: 20rpx;
		margin-top: 30rpx;
		width: 35rpx;
		height: 35rpx;
	}

	.top .title {
		text-align: center;
		font-size: 38rpx;
		color: #fff;
		line-height: 44rpx;
		padding-top: 29rpx;
	}

	.map-card {
		background-color: #fff;
		padding: 20rpx;
		width: 85%;
		margin-left: auto;
		margin-right: auto;
		border-radius: 20rpx;
	}

	map {
		width: 100%;
		height: 500rpx;
	}

	.uni-common-mt {
		margin-top: 30rpx;
		margin-bottom: 40rpx;
	}

	.content {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-wrap: wrap;
		/* #endif */
		justify-content: center;
		align-items: center;
		height: auto;
		text-align: center;
	}

	.content-text {
		font-size: 25rpx;
		color: #666;
	}

	/* 警务救助 */
	.grid-text {
		font-size: 14px;
		color: #909399;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}

	.record {
		margin-top: 20rpx;
		font-size: 25rpx;
		color: #007aff;
	}

	.btn {
		margin-top: 150rpx;
	}


	.rate-area {
		margin-top: 60rpx;
		text-align: center;
		background-color: #fff;
		padding: 30rpx 0;
		border-radius: 20rpx;
		width: 85%;
		margin-left: auto;
		margin-right: auto;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.rate-title {
		font-size: 28rpx;
		margin-bottom: 20rpx;
		display: block;
	}

	.submit-rate-btn {
		margin-top: 20rpx;
		width: 60%;
	}
	
	.ratee {
		margin-left: 140rpx;
	}
</style>